package com.chenyi.leetcode.editor.cn;

/**
 * [67]二进制求和
 *
 * @author by chenyi
 * @className AddBinary
 * @date 2022-06-22 15:01:00
 */
public class AddBinary {
    public static void main(String[] args) {
        Solution solution = new AddBinary().new Solution();
//        "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101"
//        "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"
        System.out.println(solution.addBinary(
                "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101",
                "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"));
    }

    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
            //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 二进制计算方式
         * @param a
         * @param b
         * @return
         */
        public String addBinary(String a, String b) {
            StringBuilder stringBuilder = new StringBuilder();
            int ca = 0;
            for (int i = a.length() -1, j = b.length() - 1; i >= 0 || j >=0; i--, j--) {
                int sum = ca;
                // 通过获取a.charAt位置上的ASCII码减去差值如果当前值为1(ASCII的值为49) 0(ASCII的值为48)
                // 如果当前值为1 那么就是49-48，如果当前值为0 那么就是48-48
                // 如果当前下标已经超出那么直接补0
                sum += i >= 0 ? a.charAt(i) - '0' : 0;
                sum += j >= 0 ? b.charAt(j) - '0' : 0;
                // 如果两个数都为1，那么sum的值就为2对2取余得0代表需要进1
                stringBuilder.append(sum % 2);
                // sum值为2时除2为1代表需要进1，sum值为0或1时代表不需要进1
                ca = sum / 2;
            }
            // ca如果等于1，那么代表需要进1再拼接一个值，如果不为1那么久不拼接
            stringBuilder.append(ca == 1 ? ca : "");
            // 由于我们取的方向是从后面取所以需要将当前字符反转后再输出
            return stringBuilder.reverse().toString();
        }
        public String addBinary1(String a, String b) {
            return Integer.toBinaryString(
                    Integer.parseInt(a, 2) + Integer.parseInt(b, 2)
            );
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
